from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django.db import models
# Local models and modules
from pubblr.apps.product.models import Product
from pubblr.apps.reviews.models import Review, Star
from pubblr.apps.reviews.utils import *


def index(request):
    return HttpResponse('default view when no argument is input')
    
    
def review_list(request, product_id):
    """
    Return all reviews for that product encapsulated in html elements
    """
    review_list = detail_context_render(Review.objects.all())
    return render_to_response('rev.html', {'review_list' : review_list})
    
    
def review(request, review_id):
    
    return HttpResponse('a review with review_id')


def rates_product(request, product_id, level):
    """
    Rates the Product by create Star with given level
    """
    # check whether this was spam or duplicated rating
    # (same ip or username cannot re-rates within timeframe)
    
    try: # Check whether Product is exist
        product = Product.objects.get(pk=product_id)
    except MyModel.DoesNotExist:
        if request.is_ajax(): # If this was called by ajax return fail message, so use jquery
            return HttpResponse('fail message') # To be improved
        else: 
            raise Http404
    
    star = Star(product=product, reviewer=request.user, level=level) # To be improved
    star.save()
    
    if request.is_ajax():
        return HttpResponse('success message') # To be improved
    else:
        return HttpResponseRedirect('success.html') # To be improved